/*
 * @Author: zhangxuanjiu
 * @Date: 2018-01-18 14:47:08
 * @Last Modified by: zhangxuanjiu
 * @Last Modified time: 2018-03-28 18:06:14
 */
import React from 'react'
import ReactDOM from 'react-dom'
import Cookies from 'js-cookie'
import queryString from 'query-string'
import { Router, HashRouter } from 'react-router-dom'
import { Provider } from 'react-redux'
import routes from './routes'
import configure from './store/configureStore'
import util from './lib/util'
import Preloader from './preload'
import './style/base'

global.Cookies = Cookies
global.queryString = queryString
global.util = util
util.init()
const store = configure({})
// const localConfig = localStorage.getItem('currentGroup')
// if (localConfig) {
//   store.dispatch(global.allActions.groupActions.changeCurrentGroup(JSON.parse(localConfig)))
// }

loadInfoFirst()

ReactDOM.render(
  <Provider store={store}>
    <HashRouter>
      {routes}
    </HashRouter>
  </Provider>,
  document.getElementById('root')
)

function loadAct(leftCounts) {
  if (leftCounts <= 0) {
    return
  }
  var loadSuccess = false
  setTimeout(() => {
    if (!loadSuccess && leftCounts - 1 > 0) {
      loadAct(leftCounts - 1)
    }
  }, 800)
  let userInfo = localStorage.getItem('Liangliang');
  if (userInfo) {
    store.dispatch(global.allActions.appActions.saveUserInfo(JSON.parse(userInfo)))
  }
  global.allActions.appActions.doLoadUserInfoNotSave().then(data => {
    console.warn(data)
    if(data.result == 600)
    {
      window.location.href = data.data //
    }

    if (data.result) {
      return
    }
    data.data.gameList.forEach((item, i) => {
      const cName = item.gameName + item.createMemory
      item.config = JSON.parse(item.optionJson)
      if (localStorage.getItem(cName)) {
        item.config.options = JSON.parse(localStorage.getItem(cName))
      }
      // gameData.config = conf.options
      // gameData.payTypeInfo = conf.payTypeInfo
    })
    loadSuccess = true
    localStorage.setItem('Liangliang', JSON.stringify(data));
    store.dispatch(global.allActions.appActions.saveUserInfo(data))
    store.dispatch(global.allActions.mall.loadItem)
    store.dispatch(global.allActions.appActions.queryStringExecute)
  })
}



function loadInfoFirst() {
  loadAct(5)
  const localImageStorageVersion = localStorage.getItem('imageStorageVersion')
  if (localImageStorageVersion != imageStorageVersion) {
    setTimeout(() => {
      const preloader = new Preloader()
      preloader.doload()
    }, 2000)
    localStorage.setItem('imageStorageVersion', imageStorageVersion)
  }
}

if (env !== 'dev') {
  document.addEventListener('WeixinJSBridgeReady', function onBridgeReady() {
    // 通过下面这个API隐藏右上角按钮
    WeixinJSBridge.call('hideOptionMenu')
  })
}

let result600 = sessionStorage.getItem('result600')
if (result600 == 'true') {
  sessionStorage.removeItem('result600')
  window.location.href = `${config.pre}/login/weiXin/${Cookies.get('areaCode')}`
}

// console.log(`${config.pre}/login/weiXin/${Cookies.get('areaCode')}?type=10106`)

// window.location.hash = '#/';


const ua = window.navigator.userAgent.toLowerCase()
if (ua.match(/(MicroMessenger)/i)) { // MicroMessenger
  let tryCount = 0
  let wxConf = function () {
    // 去掉hash
    const shareUrl = {
      shareUrl: window.location.href
    }
    const url = `${config.pre}/wechat/share/info/${Cookies.get('areaCode')}`
    const opt = {
      method: 'POST',
      body: JSON.stringify(shareUrl)
    }
    fetchJson(url, opt).then(data => {
      if (data.result) {
        tryCount++
        if (tryCount <= 10) {
          setTimeout(wxConf, 500)
        }
        return
      }
      let { shareAppId, shareTimestamp, shareNonceStr, shareSignature, shareLink } = data.data
      wx.config({
        debug: true,
        appId: shareAppId,
        timestamp: shareTimestamp,
        nonceStr: shareNonceStr,
        signature: shareSignature,
        jsApiList: ['onMenuShareAppMessage']
      })
      let desc = 'H5棋牌手游,无需下载安装,100%安全无挂!'
      wx.ready(function () {
        // 获取“分享给朋友”按钮点击状态及自定义分享内容接口
        wx.onMenuShareAppMessage({
          title: '游戏大厅', // 分享标题
          desc: desc, // 分享描述
          link: shareLink,
          imgUrl: `http://c-c.jiahuagame.com/game_resource/gameicon/${Cookies.get('areaCode')}/app-icon.png`, // 分享图标
          type: 'link', // 分享类型,music、video或link，不填默认为link
          trigger: function () {
            // 用户点击分享前将分享内容修改掉
            // let href = window.location.href
            // let currentGroup = JSON.parse(localStorage.getItem('currentGroup'))
            // if (href.match(/Inner/i)) {
            //   this.link = `${shareLink}/?crowdId=${currentGroup.id}`
            //   this.desc = `快来加入我的俱乐部吧，俱乐部id:${currentGroup.crowdId}`
            // } else {
            //   localStorage.removeItem('currentGroup')
            //   this.link = shareLink
            //   this.desc = '游戏大厅'
            // }
          }
        })
      })
      wx.error(function (res) {
        console.log('签名失败');
        // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
        //  alert("失败了！！")
      })
    })
  }
  wxConf()
}
